package com.lixin.smartclassroom.ui.home.tab2.activity

import android.content.Intent
import android.graphics.Color
import android.widget.CompoundButton
import android.widget.CompoundButton.OnCheckedChangeListener
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.drake.net.utils.scopeNetLife
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.api.getcoursepeizhi
import com.lixin.smartclassroom.api.setiftongbu
import com.lixin.smartclassroom.api.setquanxian
import com.lixin.smartclassroom.api.shezhiguanbishijian
import com.lixin.smartclassroom.api.yanxuecoursedetail
import com.lixin.smartclassroom.api.zhcoursedetail
import com.lixin.smartclassroom.api.zhuticoursedetail
import com.lixin.smartclassroom.common.saveSuccessDialog
import com.lixin.smartclassroom.databinding.ActivityCoursePermissionBinding
import com.lixin.smartclassroom.utils.LoginManager
import com.lixinkeji.base.BaseActivity
import com.lixinkeji.extension.dp2px
import com.lixinkeji.extension.getIntentString
import com.lixinkeji.extension.loadRound
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.setRoundRectBg
import com.lixinkeji.extension.startCode
import com.lixinkeji.extension.toast
import com.luck.picture.lib.entity.LocalMedia
import per.goweii.anylayer.AnyLayer
import per.goweii.anylayer.ktx.doOnClickToDismiss
import per.goweii.anylayer.popup.PopupLayer
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

/**
 * Description 权限设置
 * Author: lwc
 * Date:2023/12/8 11:40
 */
class CoursePermissionAct : BaseActivity<ActivityCoursePermissionBinding>() {
    override fun getViewBinding() = ActivityCoursePermissionBinding.inflate(layoutInflater)

    override fun topBarHide() = false
    override fun startPadding() = true
    override fun title() = "权限设置"
    private var courseid = ""
    private var quanxian = ""
    private var taskType = ""
    private var customerName = ""
    private var customerId = ""
    var iftongbu = ""

    override fun iniView() {
        courseid = getIntentString("courseid")
        taskType = getIntentString("type")

        scopeNetLife {
            val baseBean = getcoursepeizhi(taskType, courseid)
            if (baseBean.result == "0") {
                iftongbu = baseBean.iftongbu.toString()
                binding.switchUpdate.isChecked = baseBean.iftongbu == "1"
            }
        }


        scopeNetLife {
            when (taskType) {
                "1" -> {
                    val baseBean = zhcoursedetail(courseid)
                    if (baseBean.result == "0") {
                        quanxian = baseBean.quanxian.toString()
                        customerId = baseBean.customerids.toString()
                        if (!baseBean.endtime.isNullOrEmpty()) {
                            binding.tvTime.text = baseBean.endtime?.subSequence(0, 16)
                        }

                        initQuanxian()
                    }
                }

                "2" -> {
                    val baseBean = zhuticoursedetail(courseid)
                    if (baseBean.result == "0") {
                        quanxian = baseBean.quanxian.toString()
                        customerId = baseBean.customerids.toString()
                        if (!baseBean.endtime.isNullOrEmpty()) {
                            binding.tvTime.text = baseBean.endtime?.subSequence(0, 16)
                        }
                        initQuanxian()
                    }
                }

                "3" -> {
                    val baseBean = yanxuecoursedetail(courseid)
                    if (baseBean.result == "0") {
                        quanxian = baseBean.quanxian.toString()
                        customerId = baseBean.customerids.toString()
                        if (!baseBean.endtime.isNullOrEmpty()) {
                            binding.tvTime.text = baseBean.endtime?.subSequence(0, 16)
                        }
                        initQuanxian()
                    }
                }
            }
        }
    }

    private fun initQuanxian() {
        binding.apply {
            tvDescribe.setRoundRectBg(Color.parseColor("#F3F3F3"), dp2px(7f).toInt())
            when (quanxian) {
                "1" -> tvAuthority.text = "所有人可见"
                "2" -> tvAuthority.text = "仅学生可见"
                "3" -> {
                    tvAuthority.text = "指定用户可见"
                }

                "4" -> tvAuthority.text = "仅自己可见"
                "5" -> tvAuthority.text = "仅家长不可见"
            }
        }
    }


    override fun onClick() {
        binding.apply {
            switchUpdate.setOnCheckedChangeListener { buttonView, isChecked ->
                scopeNetLife {
                    val baseBean = when (isChecked) {
                        true -> {
                            if (iftongbu != "1")
                                setiftongbu(taskType, courseid, "1")
                            else
                                null
                        }

                        false -> {
                            if (iftongbu != "2")
                                setiftongbu(taskType, courseid, "2")
                            else
                                null
                        }
                    }
                    if (baseBean != null) {
                        if (baseBean.result == "0") {
                            iftongbu = if (isChecked) {
                                toast("同步更新成功")
                                "1"
                            } else {
                                toast("取消同步更新成功")
                                "2"
                            }

                        } else if (baseBean.result == "-2") {
                            toast(baseBean.resultNote.toString())
                            LoginManager.logout(this@CoursePermissionAct)
                        } else {
                            toast(baseBean.resultNote.toString())
                        }
                    }
                }
            }


            tvAuthority.onClick {
//                setPermissionDialog(binding.tvAuthority)

                AnyLayer.popup(binding.tvAuthority)
                    .direction(PopupLayer.Align.Direction.VERTICAL)
                    .horizontal(PopupLayer.Align.Horizontal.ALIGN_RIGHT)
                    .vertical(PopupLayer.Align.Vertical.BELOW)
                    .inside(true)
                    .backgroundColorInt(Color.parseColor("#80000000"))
                    .outsideTouchedToDismiss(true)
                    .contentView(R.layout.dialog_set_permission)
                    .bindData {

                    }.doOnClickToDismiss(R.id.btnAll) {
                        quanxian = "1"
                        tvAuthority.text = "所有人可见"
                        setquanxian()
                    }.doOnClickToDismiss(R.id.btnStudent) {
                        quanxian = "2"
                        tvAuthority.text = "仅学生可见"
                        setquanxian()
                    }.doOnClickToDismiss(R.id.btnSomePerson) {
                        startCode(SelectUserPermissionAct::class.java) {
                            putExtra("courseid", courseid)
                            putExtra("type", taskType)
                        }

                    }.doOnClickToDismiss(R.id.btnOnlySelf) {
                        quanxian = "4"
                        tvAuthority.text = "仅自己可见"
                        setquanxian()
                    }.doOnClickToDismiss(R.id.btnParent) {
                        quanxian = "5"
                        tvAuthority.text = "仅家长不可见"
                        setquanxian()
                    }
                    .show()

            }

            tvTime.onClick {
                chooseDate("设置自动关闭时间", tvTime.text.toString(), tvTime)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        courseid = data?.getStringExtra("courseid").toString()
        taskType = data?.getStringExtra("type").toString()
        customerName = data?.getStringExtra("customerName").toString()
        customerId = data?.getStringExtra("customerid").toString()
        if (customerName.isNotEmpty()) {
            binding.tvAuthority.text = customerName
        } else {
            binding.tvAuthority.text = "仅指定用户可见"
        }
        scopeNetLife {
            quanxian = "3"
            setquanxian(courseid, quanxian, taskType, customerId)
        }

    }

    private fun setquanxian() {
        scopeNetLife {
            setquanxian(courseid, quanxian, taskType)
        }
    }

    private fun chooseDate(title: String, def: String, view: TextView) {
        val format = "yyyy-MM-dd HH:mm"
        val selectedDate = Calendar.getInstance()
        if (def.isNotEmpty() && def != "不设置") {
            val df: DateFormat = SimpleDateFormat(format, Locale.getDefault())
            selectedDate.time = df.parse(def)
        }
        val startDate = Calendar.getInstance()
        val endDate = Calendar.getInstance()
        startDate.set(startDate.get(Calendar.YEAR), 0, 1, 0, 0, 0)
        endDate.set(
            endDate.get(Calendar.YEAR),
            endDate.get(Calendar.MONTH),
            endDate.get(Calendar.DAY_OF_MONTH),
            endDate.get(Calendar.HOUR),
            endDate.get(Calendar.MINUTE)
        )

        val mDatePickerView = TimePickerBuilder(this) { date, _ ->
            val df: DateFormat = SimpleDateFormat(format, Locale.getDefault())
            val time = df.format(date)
            view.text = time

            setAutoCloseData(time)


        }.setType(booleanArrayOf(true, true, true, true, true, false))// 默认全部显示
            .setCancelText("取消")//取消按钮文字
            .setSubmitText("确定")//确认按钮文字
            .setContentTextSize(16)//滚轮文字大小
            .setTitleSize(15)//标题文字大小
            .setTitleText(title)//标题文字
            .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
            .isCyclic(false)//是否循环滚动
            .setTitleColor(Color.BLACK)//标题文字颜色
            .setSubmitColor(ContextCompat.getColor(this, R.color.color_blue_44))//确定按钮文字颜色
            .setCancelColor(ContextCompat.getColor(this, R.color.color_blue_44))//取消按钮文字颜色
            .setTitleColor(ContextCompat.getColor(this, R.color.color_black_33))
            .setTitleBgColor(Color.WHITE)//标题背景颜色
            .setBgColor(Color.WHITE)//滚轮背景颜色
            .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
            .setLineSpacingMultiplier(2.5f)
            .setLabel("", "", "", "", "", "")//默认设置为年月日时分秒
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .isDialog(false)//是否显示为对话框样式
            .build()
        if (!mDatePickerView!!.isShowing) mDatePickerView.show()
    }

    private fun setAutoCloseData(time: String) {
        scopeNetLife {
            val baseBean = shezhiguanbishijian(courseid, time, taskType)
            if (baseBean.result == "0") {
                saveSuccessDialog("设置成功")
            } else {
                toast(baseBean.resultNote.toString())
            }
        }
    }

}